'use strict';

/**
 * 名片 - controller
 * **/

const { Controller } = require('egg');

class CardController extends Controller {
  async show() {
    const { ctx } = this;

    ctx.logger.info('**********根据ID获取数据*********');
    try {
      let result = '';
      if (parseInt(ctx.params.id) !== 1) {
        result = await ctx.model.Card
          .findOne({ _id: ctx.params.id });
      } else {
        if (ctx.query.cond) {
          result = await ctx.model.Card
            .findOne(JSON.parse(ctx.query.cond));
        } else {
          result = null;
        }
      }

      ctx.success(result);
    } catch (err) {
      ctx.error(err);
    }
  }

  async check() {
    const { ctx, service } = this;

    ctx.logger.info('**********增加查看数量*********');
    if (!ctx.request.body.check) {
      return ctx.fail('check is required.');
    }
    if (!ctx.request.body.openid) {
      return ctx.fail('openid is required.');
    }

    try {
      const card = await service.card.findOne({ openId: ctx.request.body.openid });

      if (card && card.check.indexOf(ctx.request.body.check) !== -1) {
        // 已经查看过
        ctx.success(true);
      } else {
        // 未查看过，记录查看记录
        await service.card.update({
          cond: {
            openId: ctx.request.body.openid,
          },
          update: {
            $push: {
              check: ctx.request.body.check,
            },
          },
        });
      }

      ctx.success(true);
    } catch (err) {
      ctx.error(err);
    }
  }

  async favorite() {
    const { ctx } = this;

    ctx.logger.info('**********收藏*********')
    if (!ctx.request.body.favorite) {
      return ctx.fail('favorite is required.');
    }
    if (!ctx.request.body.openid) {
      return ctx.fail('openid is required.');
    }

    try {
      // 记录收藏人数
      await service.card.update({
        cond: {
          openId: ctx.request.body.openid,
        },
        update: {
          $push: {
            favorite: ctx.request.body.favorite,
          },
        },
      });

      ctx.success(true);
    } catch (err) {
      ctx.error(err);
    }
  }

  async like() {
    const { ctx } = this;

    ctx.logger.info('**********点赞*********')
    if (!ctx.request.body.like) {
      return ctx.fail('like is required.');
    }
    if (!ctx.request.body.openid) {
      return ctx.fail('openid is required.');
    }

    try {
      // 记录点赞人数
      await service.card.update({
        cond: {
          openId: ctx.request.body.openid,
        },
        update: {
          $push: {
            like: ctx.request.body.like,
          },
        },
      });

      ctx.success(true);
    } catch (err) {
      ctx.error(err);
    }
  }
}

module.exports = CardController;
